using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;

namespace DA.AnimGraph.Editor {


    [NodeMenuItem(typeof(AGANode_BlendSpace2D), "Blend Space 2D")]
    internal class NodeView_BlendSpace2D : NodeViewBase {
        public override string titleText => "Blend Space 2D";

        protected override NodeViewInspectorSourceBase dataSource => inspectorData;
        NodeViewInspector_BlendSpace2D inspectorData;

        internal override void Init(AGAHandle_Node handle, AnimGraphView graphView, AGEEnvironment ageContext) {
            inspectorData = new NodeViewInspector_BlendSpace2D();
            inspectorData.SetHandle(handle);
            base.Init(handle, graphView, ageContext);
        }
    }


    internal class NodeViewInspector_BlendSpace2D : NodeViewInspectorSourceBase {

        [InspectorField] public AGAFieldModel_Vector2Link inputPosition;
        [InspectorField(label: "快捷填写")] public Action verticesGuide;
        [InspectorField(isList: true, tag: "vertices")]
        public List<AGAFieldModel_BlendSpace2DVertex> vertices;

        protected override void LoadFromModel() {
            var model = handleKeeper.handle.data.modelProperty as AGANodeModel_BlendSpace2D;
            inputPosition = model.inputPosition;
            vertices = model.vertices;
            verticesGuide = VerticesGuide;
        }

        protected override void SaveToModel() {
            handleKeeper.handle.SetDirty();
            var listView = inspectorWidgets["vertices"] as ListViewAGE;
            listView?.Rebuild();
        }

        protected override VisualElement CustomizeField(string name, InspectorFieldAttribute fieldAttribute, FieldInfo fieldInfo, AGEContext ageContext, Action inspectorChangeCallback) {
            if (fieldAttribute.tag == "vertices") {
                return BuildVertices2(name, fieldAttribute, fieldInfo, ageContext, inspectorChangeCallback);
            }
            return base.CustomizeField(name, fieldAttribute, fieldInfo, ageContext, inspectorChangeCallback);
        }
        VisualElement BuildVertices2(string name, InspectorFieldAttribute fieldAttribute, FieldInfo fieldInfo, AGEContext ageContext, Action inspectorChangeCallback) {
            var listView = new ListViewAGE() {
                title = name,
                enableCountController = true,
                itemsSource = vertices,
            };
            listView.makeItem = () => {
                var w = new FoldoutWrapper();
                w.deleteButtonClicked += (index) => {
                    vertices.RemoveAt(index);
                    inspectorChangeCallback?.Invoke();
                };
                var l = new InspectorField_BlendSpaceVertex();
                return (l, w);
            };
            listView.bindItem = (element, wrapper, index) => {
                if (element is InspectorField_BlendSpaceVertex field) {
                    field.Init(null, vertices[index], ageContext, inspectorChangeCallback);
                }
                if (wrapper is FoldoutWrapper w) {
                    w.index = index;
                    w.text = $"[{index}]";
                    w.enableDelete = true;
                }
            };
            listView.addButtonClicked = () => {
                vertices.Add(new AGAFieldModel_BlendSpace2DVertex());
                inspectorChangeCallback?.Invoke();
            };
            return listView;
        }
        VisualElement BuildVertices(string name, InspectorFieldAttribute fieldAttribute, FieldInfo fieldInfo, AGEContext ageContext, Action inspectorChangeCallback) {
            var listView = new ListView() {
                name = name,
                headerTitle = name,
                reorderable = true,
                reorderMode = ListViewReorderMode.Animated,
                selectionType = SelectionType.Single,
                showAlternatingRowBackgrounds = AlternatingRowBackground.All,
                showFoldoutHeader = true,
                showAddRemoveFooter = true,
                showBorder = true,
                fixedItemHeight = 50
            };
            listView.itemsSource = vertices;
            listView.itemIndexChanged += (oldIndex, newIndex) => {
                listView.Rebuild();
                inspectorChangeCallback?.Invoke();
            };
            listView.makeItem = () => {
                var field = new InspectorField_BlendSpaceVertex();
                return field;
            };
            listView.bindItem = (element, index) => {
                if (element is InspectorField_BlendSpaceVertex field) {
                    field.Init(null, vertices[index], ageContext, inspectorChangeCallback);
                }
            };
            listView.itemsAdded += indices => {
                foreach (var index in indices) {
                    var newItem = new AGAFieldModel_BlendSpace2DVertex() {
                        clip = new(),
                        position = default,
                    };
                    vertices[index] = newItem;
                }
                SaveToModel();
            };
            listView.itemsRemoved += indices => {
                // 引用直接关联，等待删除即可。但是要删除资源引用
                foreach (var index in indices) {
                    ageContext.resourceManager.TryRemoveResource(vertices[index].clip.clipKey);
                }
            };
            return listView;
        }

        private void VerticesGuide() {
            var window = DialogWindow.ShowWindow("快捷填写", 400, 600);

            ScrollView body = new ScrollView();
            body.Add(new Label("八方向行走，将覆盖当前填充内容"));
            var c_range = new Vector2Field("范围");
            c_range.value = new Vector2(180, 1);
            body.Add(c_range);
            var c_o = new ObjectField("中间") {
                name = "c_o",
                objectType = typeof(AnimationClip)
            };
            body.Add(c_o);
            var c_f = new ObjectField("前") {
                name = "c_f",
                objectType = typeof(AnimationClip)
            };
            body.Add(c_f);
            var c_lf = new ObjectField("左前") {
                name = "c_lf",
                objectType = typeof(AnimationClip)
            };
            body.Add(c_lf);
            var c_rf = new ObjectField("右前") {
                name = "c_rf",
                objectType = typeof(AnimationClip)
            };
            body.Add(c_rf);
            var c_l = new ObjectField("左") {
                name = "c_l",
                objectType = typeof(AnimationClip)
            };
            body.Add(c_l);
            var c_r = new ObjectField("右") {
                name = "c_r",
                objectType = typeof(AnimationClip)
            };
            body.Add(c_r);
            var c_lb = new ObjectField("左后") {
                name = "c_lb",
                objectType = typeof(AnimationClip)
            };
            body.Add(c_lb);
            var c_rb = new ObjectField("右后") {
                name = "c_rb",
                objectType = typeof(AnimationClip)
            };
            body.Add(c_rb);
            var c_b = new ObjectField("后") {
                name = "c_b",
                objectType = typeof(AnimationClip)
            };
            body.Add(c_b);

            window.UseTemplate_2Button("确认", "取消", body, index => {
                if (index == 1) {
                    vertices.Clear();
                    Vector2 range = c_range.value;
                    var o = (AnimationClip)c_o.value;
                    var f = (AnimationClip)c_f.value;
                    var lf = (AnimationClip)c_lf.value;
                    var rf = (AnimationClip)c_rf.value;
                    var l = (AnimationClip)c_l.value;
                    var r = (AnimationClip)c_r.value;
                    var lb = (AnimationClip)c_lb.value;
                    var rb = (AnimationClip)c_rb.value;
                    var b = (AnimationClip)c_b.value;

                    var uuid = ageContext.resourceManager.AddResource(o, AGAResourceType.Clip);
                    vertices.Add(new AGAFieldModel_BlendSpace2DVertex() { clip = new() { clipKey = uuid }, position = new(0, 0) });
                    uuid = ageContext.resourceManager.AddResource(o, AGAResourceType.Clip);
                    vertices.Add(new AGAFieldModel_BlendSpace2DVertex() { clip = new() { clipKey = uuid }, position = new(range.x, 0) });
                    uuid = ageContext.resourceManager.AddResource(o, AGAResourceType.Clip);
                    vertices.Add(new AGAFieldModel_BlendSpace2DVertex() { clip = new() { clipKey = uuid }, position = new(-range.x, 0) });

                    uuid = ageContext.resourceManager.AddResource(f, AGAResourceType.Clip);
                    vertices.Add(new AGAFieldModel_BlendSpace2DVertex() { clip = new() { clipKey = uuid }, position = new(0, range.y) });
                    uuid = ageContext.resourceManager.AddResource(rf, AGAResourceType.Clip);
                    vertices.Add(new AGAFieldModel_BlendSpace2DVertex() { clip = new() { clipKey = uuid }, position = new(range.x * 0.25f, range.y) });
                    uuid = ageContext.resourceManager.AddResource(lf, AGAResourceType.Clip);
                    vertices.Add(new AGAFieldModel_BlendSpace2DVertex() { clip = new() { clipKey = uuid }, position = new(-range.x * 0.25f, range.y) });
                    uuid = ageContext.resourceManager.AddResource(r, AGAResourceType.Clip);
                    vertices.Add(new AGAFieldModel_BlendSpace2DVertex() { clip = new() { clipKey = uuid }, position = new(range.x * 0.5f, range.y) });
                    uuid = ageContext.resourceManager.AddResource(l, AGAResourceType.Clip);
                    vertices.Add(new AGAFieldModel_BlendSpace2DVertex() { clip = new() { clipKey = uuid }, position = new(-range.x * 0.5f, range.y) });
                    uuid = ageContext.resourceManager.AddResource(rb, AGAResourceType.Clip);
                    vertices.Add(new AGAFieldModel_BlendSpace2DVertex() { clip = new() { clipKey = uuid }, position = new(range.x * 0.75f, range.y) });
                    uuid = ageContext.resourceManager.AddResource(lb, AGAResourceType.Clip);
                    vertices.Add(new AGAFieldModel_BlendSpace2DVertex() { clip = new() { clipKey = uuid }, position = new(-range.x * 0.75f, range.y) });

                    uuid = ageContext.resourceManager.AddResource(b, AGAResourceType.Clip);
                    vertices.Add(new AGAFieldModel_BlendSpace2DVertex() { clip = new() { clipKey = uuid }, position = new(range.x, range.y) });
                    uuid = ageContext.resourceManager.AddResource(b, AGAResourceType.Clip);
                    vertices.Add(new AGAFieldModel_BlendSpace2DVertex() { clip = new() { clipKey = uuid }, position = new(-range.x, range.y) });

                    SaveToModel();
                }
            }, false);
        }
    }

}
